package router

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gofrs/uuid"
	log "github.com/sirupsen/logrus"
	"queue-gateway/amqp"
	"queue-gateway/common"
	"queue-gateway/config"
)

// ServerHandler 统一处理入口
func ServerHandler(c *gin.Context) {
	subpath := c.Param("upstream")
	path := c.Param("path")
	rs, _ := uuid.NewV4()
	msgID := fmt.Sprintf("%s%s_%s_%s", subpath, path, config.BalanceIP, rs.String())
	log.Debugf("subpath%s:, path:%s; msgId: %s", subpath, path, msgID)

	//获取POST数据
	raw, err := c.GetRawData()
	log.Debugf("raw data is: %s", string(raw))
	if producer, ok := amqp.Producers[subpath]; ok {
		headers := map[string]interface{}{"taskid": msgID, "url": path}
		producer.Publish(raw, msgID, headers)
	} else {
		print(44444)
		panic(common.NewBadRequst(subpath, 10, fmt.Sprintf("upstream:%s", subpath)))
	}

	result := genCallbackHttpResponse(msgID)
	if result.Status == 408 {
		panic(common.NewBadRequst(subpath, 11, fmt.Sprintf("timeout:%v",
			config.ServiceConfig.Upstreams[subpath].TimeOut)))
	}
	resultBody := result.Body
	if err != nil {
		log.Errorf(err.Error())
		panic(err)
	}

	c.JSON(result.Status, resultBody)

}
